﻿/// <reference path="../../js/data.js" />
/// <reference path="../../js/UI.js" />
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    var nav = WinJS.Navigation;

    WinJS.UI.Pages.define("/pages/rssSettings/rssSettingsPage.html", {

        navigateToRssSettings: function (groupInfo) {
            nav.navigate("/pages/rssSettings/rssSettingsPage.html", groupInfo);
        },

        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            setFormValues(options);

            id("saveAndGo").addEventListener("click", saveAndGoCommand, false);
            id("saveToFile").addEventListener("click", saveToFileCommand, false);
            id("loadFromFile").addEventListener("click", loadFromFileCommand, false);
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        }
    });

    function saveAndGoCommand() {
        var gameInfo = getFormValues();
        Settings.Manager.setRoamingSettings(gameInfo);
        nav.navigate("../pages/groupedItems/groupedItems.html", {});
        Data.Manager.refreshRSS();
    }

    function saveToFileCommand() {
        var savePicker = new Windows.Storage.Pickers.FileSavePicker();
        savePicker.defaultFileExtension = ".json";
        savePicker.fileTypeChoices.insert("JSON", [".json"]);
        savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
        savePicker.suggestedFileName = id("group-title").value + "RssSettings";

        savePicker.pickSaveFileAsync().then(function (file) {
            try {
                var groupInfo = getFormValues();
                var textToWrite = JSON.stringify(groupInfo);
                Windows.Storage.FileIO.writeTextAsync(file, textToWrite).then(
                    function (success) {
                        UI.alert("Successfully saved file!");
                    },
                    function (error) {
                        UI.alert("Couldn't save file!");
                    });
            }
            catch (e) {
                UI.alert("Couldn't save file!");
            }
        });
    }

    function loadFromFileCommand() {
        var openPicker = Windows.Storage.Pickers.FileOpenPicker();

        openPicker.fileTypeFilter.append("*");
        openPicker.pickSingleFileAsync().then(function (storageFile) {
            Windows.Storage.FileIO.readTextAsync(storageFile).then(
                function (str) {
                    try{
                        var groupInfo = JSON.parse(str);
                        setFormValues(groupInfo);
                        //UI.alert("Successfully loaded file!");
                    }
                    catch (e) {
                        UI.alert("Couldn't load rss info file!");
                    }
                },
                function (error) {
                    UI.alert("Couldn't load rss info file!");
                });
        });
    }


    function id(id) {
        return document.getElementById(id);
    }

    function setTagAttrPrefix(obj, tagId, attrId, prefixId) {
        id(tagId).value = obj.tagName || "";
        id(attrId).value = obj.attributeName || "";

        if (prefixId) {
            id(prefixId).value = obj.prefix || "";
        }
    }

    function setFormValues(groupInfo) {
        id("group-title").value = groupInfo.title;
        id("group-subtitle").value = groupInfo.subtitle;
        id("group-image-url").value = groupInfo.backgroundImage;
        id("group-url").value = groupInfo.url;
        id("group-description").value = groupInfo.description;

        id("item-tagName").value = groupInfo.itemInfo.tagName;
        setTagAttrPrefix(groupInfo.itemInfo.title, "item-title-tagName", "item-title-attributeName", "item-title-prefix");
        setTagAttrPrefix(groupInfo.itemInfo.subtitle, "item-subtitle-tagName", "item-subtitle-attributeName", "item-subtitle-prefix");
        setTagAttrPrefix(groupInfo.itemInfo.description, "item-description-tagName", "item-description-attributeName", "item-description-prefix");
        setTagAttrPrefix(groupInfo.itemInfo.content, "item-content-tagName", "item-content-attributeName", "item-content-prefix");
        setTagAttrPrefix(groupInfo.itemInfo.moreInfo, "item-moreInfo-tagName", "item-moreInfo-attributeName", null);
        setTagAttrPrefix(groupInfo.itemInfo.image, "item-image-tagName", "item-image-attributeName", null);
    }


    function getTagAttrPrefix(tagId, attrId, prefixId) {
        var obj = {};
        obj.tagName = id(tagId).value;
        obj.attributeName = id(attrId).value;

        if (prefixId) {
            obj.prefix = id(prefixId).value;
        }

        return obj;
    }

    function getFormValues() {
        var groupInfo = { key: "0" };

        groupInfo.title = id("group-title").value;
        groupInfo.subtitle = id("group-subtitle").value;
        groupInfo.backgroundImage = id("group-image-url").value;
        groupInfo.url = id("group-url").value;
        groupInfo.description = id("group-description").value;

        groupInfo.itemInfo = {};
        groupInfo.itemInfo.tagName = id("item-tagName").value;
        groupInfo.itemInfo.title = getTagAttrPrefix("item-title-tagName", "item-title-attributeName", "item-title-prefix");
        groupInfo.itemInfo.subtitle = getTagAttrPrefix("item-subtitle-tagName", "item-subtitle-attributeName", "item-subtitle-prefix");
        groupInfo.itemInfo.description = getTagAttrPrefix("item-description-tagName", "item-description-attributeName", "item-description-prefix");
        groupInfo.itemInfo.content = getTagAttrPrefix("item-content-tagName", "item-content-attributeName", "item-content-prefix");
        groupInfo.itemInfo.moreInfo = getTagAttrPrefix("item-moreInfo-tagName", "item-moreInfo-attributeName", null);
        groupInfo.itemInfo.image = getTagAttrPrefix("item-image-tagName", "item-image-attributeName", null);

        return groupInfo;
    }

})();
